package interview.sync.lock;/*

 */

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @ClassName LockThreadDemo
 * @Author Final
 * @Project DataStructures
 */
class Share{
    public int number=0;

    public Lock lock=new ReentrantLock(true);

    public Condition condition=lock.newCondition();

    public void incr() throws InterruptedException{

        lock.lock();
        try {
            while (number!=0) {
                condition.await();
            }
            number++;

            System.out.println(number);
            condition.signalAll();
        } finally {
            lock.unlock();
        }


    }

    public void decr() throws InterruptedException {
        lock.lock();

        try {
            while (number!=1){
                condition.await();
            }
            number--;
            condition.signalAll();
        }finally {
            lock.unlock();
        }
    }
}

public class LockThreadDemo {

    public static void main(String[] args) {

        Share share=new Share();
        new Thread(()->{
            for (int i=0;i<10;i++){
                try {
                    share.incr();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"aa").start();

        new Thread(()->{
            for (int i=0;i<10;i++){
                try {
                    share.decr();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"bb").start();
    }
}
